from PIL import Image, ImageDraw
import numpy as np

def test1():
    n1 = np.array([1,2,3,4,5,6])
    print("-----")
    print(n1)

    n2 = n1.reshape(3,2)
    print("-----")
    print(n2)
    print(n2.shape)

    print("-----")
    n3 = np.array([[1, 2], [3, 4], [5, 6]])
    print(n3)
    print(n3.shape)  # (3, 2)


def test3():
    # 创建一个 5x4 的黑色图像
    n3 = np.array([
        [0, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 0, 1],
        [1, 1, 1, 1, 1]])
    image_data = np.where(n3 == 1, 255, 0).astype(np.uint8)  # 将矩阵转换为图像 0 -> 黑色(0), 1 -> 白色(255)
    image = Image.fromarray(image_data, mode='L')  # 'L'表示8位灰度图像
    image.save('coordinate_test.png')  # 保存为PNG文件

def test4():
    DX, DY = 4000, 3000
    # (1) 使用spark生成的二进制文件作为数据源
    with open("D:\\temp\\jl\\grids.data", "rb") as f:
        grid = np.fromfile(f, dtype=np.byte, count=DX * DY)
        arr = []
        i = 0
        while i != DY:
            arr.append(grid[i * 4000: i * 4000 + 4000])
            i = i + 1
    print(type(arr))
    matrix2 = np.array(arr)
    print(matrix2.shape)
    image_data2 = np.where(matrix2 == 1, 255, 0).astype(np.uint8) # 将矩阵转换为图像 0 -> 黑色(0), 1 -> 白色(255)
    # 'L'表示8位灰度图像, transpose(Image.FLIP_TOP_BOTTOM)y轴翻转
    image2 = Image.fromarray(image_data2, mode='L').transpose(Image.FLIP_TOP_BOTTOM)
    image2.save('binary_image2.png') # 保存为PNG文件
    # 如果需要显示图像（可选）
    image2.show()

def test2():
    # 假设你有一个4000x3000的二维矩阵，名为matrix
    DX, DY = 4000, 3000

    # (1) 使用spark生成的二进制文件作为数据源
    with open("D:\\temp\\jl\\grids.data", "rb") as f:
        grid = np.fromfile(f, dtype=np.byte, count=DX * DY)
        arr = []
        i = 0
        while i != DY:
            arr.append(grid[i * 4000: i * 4000 + 4000])
            i = i + 1
    # 1:     1, 2, 3, ...., 3999,4000
    # 2:     1, 2, 3, ...., 3999,4000
    # 3:     1, 2, 3, ...., 3999,4000
    # ......
    # 3000:  1, 2, 3, ...., 3999,4000
    # 共3000行,4000列。对np来说，shape是(3000, 4000)
    matrix = grid.reshape(DY, DX)
    print(matrix)
    print(matrix.shape)
    # 将矩阵转换为图像 0 -> 黑色(0), 1 -> 白色(255)
    image_data = np.where(matrix == 1, 255, 0).astype(np.uint8)
    # 创建图像对象, 'L'表示8位灰度图像, transpose(Image.FLIP_TOP_BOTTOM)y轴翻转
    image = Image.fromarray(image_data, mode='L')

    draw = ImageDraw.Draw(image)
    draw.rectangle((2048, 2048, 2048+512, 2048+512))
    draw.rectangle((1536, 2048, 1536+512, 2048+512))

    image = image.transpose(Image.FLIP_TOP_BOTTOM)

    image.save('binary_image.png')  # 保存为PNG文件
    # 如果需要显示图像（可选）
    image.show()



if __name__ == "__main__":
    # test1()
    test2()
    # test3()
    # test4()